package com.only4play.session.impl;

import com.only4play.session.SessionMappingStorage;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liyuncong
 * @version 1.0
 * @file LocalSessionMappingStorage
 * @brief 本地session关系存储
 * @details 本地session关系存储
 * @date 2023-11-19
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2023-11-19               liyuncong          Created
 */
public class LocalSessionMappingStorage implements SessionMappingStorage {

    private final Map<String, HttpSession> tokenSessionMap = new ConcurrentHashMap<>();
    private final Map<String, String> sessionTokenMap = new ConcurrentHashMap<>();

    @Override
    public void addSessionById(String accessToken, HttpSession session) {
        sessionTokenMap.put(session.getId(), accessToken);
        tokenSessionMap.put(accessToken, session);
    }

    @Override
    public void removeBySessionById(String sessionId) {
        String accessToken = sessionTokenMap.getOrDefault(sessionId, null);
        if (StringUtils.isNotBlank(accessToken)) {
            tokenSessionMap.remove(accessToken);
        }
        sessionTokenMap.remove(sessionId);
    }

    @Override
    public HttpSession removeSessionByMappingId(String accessToken) {
        HttpSession session = tokenSessionMap.getOrDefault(accessToken, null);
        if (Objects.nonNull(session)) {
            removeBySessionById(session.getId());
        }
        return session;
    }
}
